package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApCollectService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ApCollectServiceImpl implements ApCollectService {


    private final CacheService cacheService;

    private final KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 文章收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        // TODO：未做持久化
        // 1、检查是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2、检查参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String key;
        UpdateArticleMess mess=new UpdateArticleMess();
        if(dto.getType()==0){
            key = BehaviorConstants.COLLECT_ARTICLE+"_"+dto.getEntryId();
        }else{
            key = BehaviorConstants.COLLECT_DYNAMIC+"_"+dto.getEntryId();
        }
        if(dto.getOperation()==0){
            mess.setAdd(1);
            cacheService.hPut(key,user.getId().toString(), "0");
        }else{
            mess.setAdd(-1);
            cacheService.hDelete(key,user.getId().toString());
        }
        mess.setArticleId(dto.getEntryId());
        mess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
        asyncKafkaStreamUpdateCollectionCountToDb(mess);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 使用kafka stream 更新 Db中的 文章收藏数量
     * @Author huangjianfei
     * @Since 2024/11/16
     * @Version day11
     * @param mess
     */
    private void asyncKafkaStreamUpdateCollectionCountToDb(UpdateArticleMess mess) {
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));
    }
}
